package org.xnsg.app.conf;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.eova.config.EovaConfig;
import com.eova.core.button.ButtonController;
import com.eova.core.menu.MenuController;
import com.eova.model.*;
import com.eova.service.ServiceManager;
import com.eova.template.single.SingleController;
import com.eova.widget.WidgetController;
import com.eova.widget.form.FormController;
import com.eova.widget.grid.GridController;
import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnsg.app.controller.*;
import org.xnsg.app.model.Announcements;
import org.xnsg.app.model.aj_dw_files;
import org.xnsg.app.model.user_tables;

import java.sql.SQLException;

/**
 * @author zhaopan
 * @date :2017/4/15
 * @Description:入口
 */
public class XnsgConfig extends JFinalConfig {
    //private final static Logger logger = LogManager.getLogger(XnsgConfig.class);
    private final static Logger logger = LoggerFactory.getLogger(XnsgConfig.class);
    // final static Logger logger = LogManager.getLogger(XnsgConfig.class);

    /**
     * 配置常量
     */
    public void configConstant(Constants me) {
        me.setDevMode(true);

        me.setEncoding("utf-8");

        //me.setViewType(ViewType.JSP);
        PropKit.use("config/domain.properties");
        //PropKit.use("config/eova.properties");
        //PropKit.use("config/jdbc.properties");
        //arg0.setBaseViewPath("template");//页面模板根路径

        // arg0.setFreeMarkerViewExtension(".ftl");//freemarker 模板后缀名
        //me.setMainRenderFactory(new BeetlRenderFactory());
    }

    /**
     * 配置处理器
     */
    public void configHandler(Handlers me) {
        // me.add(new ContextPathHandler("base"));//添加项目contextPath,以便在页面直接获取该值 ${base?if_exists}
        DruidStatViewHandler dvh = new DruidStatViewHandler("/druid");
        me.add(dvh);
    }

    /**
     * 配置拦截器
     */
    public void configInterceptor(Interceptors me) {
        System.err.println("Config Interceptors Starting...");
        //me.add(new LoginInterceptor());

    }

    /**
     * 配置路由
     */
    public void configRoute(Routes me) {
        //arg0.add("/", HelloController.class);//添加项目路由，类似于struts的action 配置文件，此处配置controller名，action名称对应方法名
        //arg0.add("/blog", BlogController.class);
        System.err.println("Config Routes Starting...");
        //me.add("/", LoginController.class);

        me.add("single_grid", SingleController.class);
        //me.add("single_tree", SingleTreeController.class);
        //me.add("master_slave_grid", MasterSlaveController.class);
        //me.add("tree_grid", TreeToGridController.class);
        me.add("/user", UserController.class);
        me.add("/login", LoginController.class);
        me.add("/production",ProductionController.class);
        me.add("/widget", WidgetController.class);
        //me.add("/upload", UploadController.class);
        me.add("/form", FormController.class);
        me.add("/grid", GridController.class);
        me.add("/grid_event", GridEventController.class);
        me.add("/app_grid",AppGridController.class);
        me.add("/inspect",InspectController.class);
        me.add("/special",SpecialController.class);
        //me.add("/tree", TreeController.class);
       // me.add("/treegrid", TreeGridController.class);
        //me.add("/meta", MetaController.class);
        me.add("/menu", MenuController.class);
        me.add("/button", ButtonController.class);
        //me.add("/auth", AuthController.class);
        //me.add("/task", TaskController.class);
    }

    public void afterJFinalStart() {
        // 由于我们用到freemarker，所以在此进行freemarker配置文件的装载
        // Properties p = loadPropertyFile("freemarker.properties");

        //FreeMarkerRender.setProperties(p);

    }

    /**
     * 配置插件
     */
    public void configPlugin(Plugins plugins) {
        logger.info("配置MainDruid数据库连接池");

        //从配置文件中获取数据库配置项
        //PropertyConfig config = PropertyConfig.me();
        DruidPlugin mainDruid = new DruidPlugin(
                PropKit.get("main_url"),
                PropKit.get("main_user"),
                PropKit.get("main_pwd"),
                PropKit.get("driver_class"));
        mainDruid.set(
                PropKit.getInt("db.initialSize"),
                PropKit.getInt("db.minIdle"),
                PropKit.getInt("db.maxActive"));
        mainDruid.setValidationQuery(PropKit.get("db.validationQuery"));
        mainDruid.setMaxWait(PropKit.getInt("db.maxWait"));
        mainDruid.setMinEvictableIdleTimeMillis(PropKit.getInt("db.minEvictableIdleTimeMillis"));
        mainDruid.setTimeBetweenEvictionRunsMillis(PropKit.getInt("db.timeBetweenEvictionRunsMillis"));
        //mainDruid.setFilters(PropKit.get("druid.filters"));
        mainDruid.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.maxPoolPreparedStatementPerConnectionSize"));
        logger.info("configPlugin 配置Druid数据库连接池过滤器配制");
        StatFilter stat = new StatFilter();

        mainDruid.addFilter(stat);
        //Log4jFilter log4jFilter = new Log4jFilter();
        //mainDruid.addFilter(log4jFilter);
        WallFilter wall = new WallFilter();
        wall.setDbType(PropKit.get("db.type"));
        WallConfig config = new WallConfig();
        config.setFunctionCheck(false); // 支持数据库函数
        wall.setConfig(config);
        mainDruid.addFilter(wall);

        ActiveRecordPlugin arp = new ActiveRecordPlugin("main", mainDruid);
        arp.setTransactionLevel(PropKit.getInt("transaction_level"));
        arp.setDevMode(PropKit.getBoolean("devMode"));
        arp.setShowSql(PropKit.getBoolean("showSql"));
        arp.setDialect(new OracleDialect());
        arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));


        //DB-实体
        arp.addMapping("announcements", Announcements.class);
        arp.addMapping("aj_dw_files", aj_dw_files.class);
        arp.addMapping("user_tables", user_tables.class);
        plugins.add(mainDruid).add(arp);
//        logger.info("SqlXmlPlugin 解析并缓存 xml sql");
//        plugins.add(new SqlXmlPlugin());

        logger.info("配置eovaDruid数据库连接池");
        //从配置文件中获取数据库配置项
        //PropertyConfig config = PropertyConfig.me();
        DruidPlugin eovaDruid = new DruidPlugin(
                PropKit.get("eova_url"),
                PropKit.get("eova_user"),
                PropKit.get("eova_pwd"),
                PropKit.get("driver_class"));
        eovaDruid.set(
                PropKit.getInt("db.initialSize"),
                PropKit.getInt("db.minIdle"),
                PropKit.getInt("db.maxActive"));
        eovaDruid.setValidationQuery(PropKit.get("db.validationQuery"));
        eovaDruid.setMaxWait(PropKit.getInt("db.maxWait"));
        eovaDruid.setMinEvictableIdleTimeMillis(PropKit.getInt("db.minEvictableIdleTimeMillis"));
        eovaDruid.setTimeBetweenEvictionRunsMillis(PropKit.getInt("db.timeBetweenEvictionRunsMillis"));
        //mainDruid.setFilters(PropKit.get("druid.filters"));
        eovaDruid.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.maxPoolPreparedStatementPerConnectionSize"));
        logger.info("configPlugin 配置Druid数据库连接池过滤器配制");

        eovaDruid.addFilter(stat);
        eovaDruid.addFilter(wall);
        //eovaDruid.addFilter(log4jFilter);
        ActiveRecordPlugin earp = new ActiveRecordPlugin("eova", eovaDruid);
        earp.setTransactionLevel(PropKit.getInt("transaction_level"));
        earp.setDevMode(PropKit.getBoolean("devMode"));
        earp.setShowSql(PropKit.getBoolean("showSql"));
        earp.setDialect(new OracleDialect());
        earp.setContainerFactory(new CaseInsensitiveContainerFactory(true));


        earp.addMapping("eova_object", MetaObject.class);
        earp.addMapping("eova_field", MetaField.class);
        earp.addMapping("eova_button", Button.class);
        earp.addMapping("eova_menu", Menu.class);
        earp.addMapping("eova_menu_object", MenuObject.class);
        earp.addMapping("eova_user", User.class);
        earp.addMapping("eova_role", Role.class);
        earp.addMapping("eova_role_btn", RoleBtn.class);
        earp.addMapping("eova_log", EovaLog.class);
        earp.addMapping("eova_task", Task.class);
        earp.addMapping("eova_widget", Widget.class);
        plugins.add(eovaDruid).add(earp);
        try {
            EovaConfig.EOVA_DBTYPE=JdbcUtils.getDbType(PropKit.get("eova_url"), JdbcUtils.getDriverClassName(PropKit.get("eova_url")));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        logger.info("EhCachePlugin EhCache缓存");
        ServiceManager.init();
        plugins.add(new EhCachePlugin());

    }

    /**
     * 建议使用 JFinal 手册推荐的方式启动项目
     * 运行此 main 方法可以启动项目，此main方法可以放置在任意的Class类定义中，不一定要放于此
     */
    public static void main(String[] args) {
        logger.info(" start ...");
        //DynamicParse.buildSql(exp, new Object[]{this.getSessionAttr("user")});
        //
        //
        JFinal.start("target/xnsg-app", 80, "/", 5);//启动配置项
    }

}
